/*
 * @Description: 
 * @Author: charles
 * @Date: 2021-10-21 15:21:28
 * @LastEditors: charles
 * @LastEditTime: 2021-10-25 22:50:33
 */
import { createRouter, createWebHistory } from 'vue-router'
import store from '../store'

const routes = [
  {
    path: '/',
    redirect: '/home'
  }, {
    path: '/register',
    component: () => import(/* webpackChunkName: "register" */ '../pages/Register.vue')

  }, {
    path: '/login',
    component: () => import(/* webpackChunkName: "login" */ '../pages/Login.vue')
  }, {
    path: '/home',
    component: () => import(/* webpackChunkName: "home" */ '../pages/Home.vue'),
    beforeEnter(to,from){
      // 通过token获取用户信息，存放到vuex
      store.dispatch('user/loadUser');
    },
    children: [{
      path: 'index',
      component: () => import(/* webpackChunkName: "home_index" */ '../pages/home/Index.vue'),
    },{
      path: 'orders',
      component: () => import(/* webpackChunkName: "home_orders" */ '../pages/home/orders/List.vue'),
    },{
      path: 'confirm_order',
      name:'confirm_order',
      component: () => import(/* webpackChunkName: "home_orders" */ '../pages/home/orders/Confirm.vue'),
    },{
      path: 'me',
      component: () => import(/* webpackChunkName: "home_me" */ '../pages/home/Me.vue'),
    }]
  },

  // fullpage
  {
    path: '/address_edit',
    name: 'address_edit',
    component: () => import(/* webpackChunkName: "home_me" */ '../pages/home/address/Edit.vue'),
  },{
    path: '/address',
    name:'address',
    component: () => import(/* webpackChunkName: "home_me" */ '../pages/home/address/List.vue'),
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to,from,next)=>{
  // 白名单
  let paths = ["/login","/register"]
  if(paths.indexOf(to.path)!=-1){
    next();
  }
  // 验证token
  let token = localStorage.getItem('token');
  if(!token){
    next('/login')
  } else {
    next();
  }
})

export default router
